define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'qingdongwms/stock/purchase/index',
                    add_url: 'qingdongwms/stock/purchase/add',
                    edit_url: 'qingdongwms/stock/purchase/edit',
                    detail_url: 'qingdongwms/stock/purchase/detail',
                    del_url: 'qingdongwms/stock/purchase/del',
                    table: 'purchase'
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        {field: 'state', checkbox: true},
                        {
                            field : 'num', title : '采购单编号', fixedColumns : true, formatter : function (value, row, index) {
                                if(value ==''){
                                    value = '无';
                                }
                                return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-detail'>" + value + "</a>";
                            },operate:'like'
                        },
                        {field: 'date', title: __('采购日期')},
                        {field: 'money', title: __('金额')},
                        {field: 'supplier.name', title: __('供应商'), operate:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
                //启用普通表单搜索
                search:false,
                commonSearch: true,
                searchFormVisible: true,
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $('.btn-editone').html('编辑');
                    $('.fa-pencil').remove();
                    $('.btn-delone').html('删除');
                    $('.fa-trash').remove();
                    $('.btn-editone').removeClass('btn-success')
                    $('.btn-editone').removeClass('btn')
                    $('.btn-delone').removeClass('btn')
                    $('.btn-delone').removeClass('btn-danger')
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-add").data("area",["80%","80%"]);
                    $(".btn-edit").data("area",["80%","80%"]);
                    $(".btn-editone").data("area",["80%","80%"]);

                }
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            $('.search').hide();
            $('.btn-import').hide();
            $(document).on('click', '.show-detail', function (data) {
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose : false,
                    shade      : [0.3, '#393D49'],
                    area       : area,
                    callback   : function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + $(this).data('id'), '采购单', options);
            });
        },
        add: function () {
            Controller.api.bindevent();

        },

        edit: function () {
            Controller.api.bindevent();
        },
        tabledetail    : {
            basic:function (){},
            product: function () {

                //操作日志
                var table2 = $("#operation_product");
                // 初始化表格
                table2.bootstrapTable({
                    url          : 'qingdongwms/stock/purchase/get_instock_product?instock_id='+Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar: "#toolbar_product",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'name', title: __('名称')},
                            {field: 'unit', title: __('单位')},
                            {field: 'number', title: __('采购数量')},
                            {field: 'price', title: __('采购单价（元）')},
                            {field: 'total_price', title: __('采购价格小计（元）'), formatter : function (value, row, index) {

                                    return row.price * row.number;
                                }},
                        ]
                    ]
                });
                Table.api.bindevent(table2);
            },

        },
        detail : function () {
            // 初始化表格参数配置
            Table.api.init({});
            $('.stafflist').popover({
                placement : 'bottom',
                trigger : 'hover'
            });
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.tabledetail[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            //编辑
            $(document).on('click','#edits',function () {
                var id=$('#instockId').val();
                Fast.api.open("qingdongwms/stock/purchase/edit?ids="+id, "采购单编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%", "95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            });
            //删除
            $("#dels").on('click',function(){
                var id=$('#instockId').val();
                Layer.confirm('确定删除采购单吗？', {
                    btn: ['确定','取消']
                },function(index, layero){
                    Fast.api.ajax("qingdongwms/stock/purchase/del?ids="+id,function(data,ret){
                        if(ret.code == 1){
                            Layer.close(index);
                            parent.location.reload();
                        }
                    },function(data,ret){
                    });

                });
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent : function () {
                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                });
                $(".selectpage").data("params", function (obj) {
                    var customer_id=$('#customer').val()
                    //obj为SelectPage对象
                    return {ids: customer_id};
                });

                function set_money(){
                    var $price = $('.price');
                    var $number = $('.number');
                    var price=0;
                    $.each($price, function (index, item) {
                        var p = $(item).val(), n = $number.eq(index).val();
                        p = parseFloat(p);
                        n = parseInt(n);
                        price += p * n;
                    });
                    $('#c-money').val(price);
                }
                $(document).on("click", ".select-product", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url"), __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                            $this.parent().parent().next('td').find('input').val(data.price);
                            $this.parent().parent().parent().find('.price2').val(data.wholesale);

                            $this.parent().parent().next('td').next('td').find('input').val(data.wholesale);

                            $(".fieldlist input:eq(2)").trigger("change");
                        },area:["100%", "100%"]});
                }).on("change", ".price", function(){
                    set_money();
                }).on("change", ".number", function(){
                    set_money();
                }).on("change", "#ratio_id", function(){
                    var ratio=$('#ratio_id').find('option:selected').data('ratio');
                    if(!ratio){
                        $('.table_ratio').hide();
                        return false;
                    }
                    var html="";
                    $.each(ratio,function (index,item){
                        html+="<tr>" +
                            "<td>"+item.ratio+"%<input type='hidden' name='row[ratios]["+index+"][ratio]' value='"+item.ratio+"'></td>" +
                            "<td><input data-source=\"qingdongwms/customer/customer/getteam\"" +
                            "class=\"form-control selectpage\" name=\"row[ratios]["+index+"][staff_id]\" placeholder=\"请选择团队成员\" type=\"text\" value=\"\"></td>" +
                            "</tr>";
                    });
                    $('.table_ratio').find('tbody').html(html);
                    $('.table_ratio').show();
                    Form.events.selectpage($("form"));

                    $(".selectpage").data("params", function (obj) {
                        var customer_id=$('#customer').val()
                        if(!customer_id){
                            layer.msg('请先选择客户');
                            return false;
                        }
                        //obj为SelectPage对象
                        return {ids: customer_id};
                    });
                })

                require(['backend/qingdongwms/common/common'])
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                    Fast.api.close(data);//这里是重点
                });
            }
        }

    };
    return Controller;
});